package GUI;

import CDB.Proveedores;
import Negocios.ControlProviders;
import Negocios.ControlStock;
import java.awt.HeadlessException;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author lightemp
 */
public class AltaStock extends javax.swing.JInternalFrame {

    public AltaStock() {
        initComponents();
        CargaCombo();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel7 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jpnStock = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        Cantidad = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        Precio = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        txtCantidad = new javax.swing.JTextField();
        txtMinimo = new javax.swing.JTextField();
        txtPrecioGranel = new javax.swing.JTextField();
        cmbProveedor = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();

        jLabel7.setText("jLabel7");

        jTextField5.setText("jTextField5");

        jLabel8.setText("jLabel8");

        jpnStock.setBackground(new java.awt.Color(255, 255, 255));
        jpnStock.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel1.setText("Nombre");

        Cantidad.setText("Cantidad");

        jLabel3.setText("Minimo");

        Precio.setText("Precio Granel");

        jLabel5.setText("Proveedor");

        txtCantidad.setText("0");
        txtCantidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCantidadKeyTyped(evt);
            }
        });

        txtMinimo.setText("0");
        txtMinimo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMinimoKeyTyped(evt);
            }
        });

        txtPrecioGranel.setText("0");
        txtPrecioGranel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtPrecioGranelKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jpnStockLayout = new javax.swing.GroupLayout(jpnStock);
        jpnStock.setLayout(jpnStockLayout);
        jpnStockLayout.setHorizontalGroup(
            jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnStockLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmbProveedor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtNombre)
                    .addGroup(jpnStockLayout.createSequentialGroup()
                        .addGroup(jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(jpnStockLayout.createSequentialGroup()
                                .addGroup(jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(Cantidad, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jpnStockLayout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addGap(18, 18, 18)
                                        .addComponent(Precio))
                                    .addGroup(jpnStockLayout.createSequentialGroup()
                                        .addComponent(txtMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(txtPrecioGranel, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addComponent(jLabel5))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jpnStockLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {Cantidad, Precio, jLabel1, jLabel3, jLabel5, txtCantidad, txtMinimo, txtPrecioGranel});

        jpnStockLayout.setVerticalGroup(
            jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnStockLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Cantidad)
                    .addComponent(jLabel3)
                    .addComponent(Precio))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtPrecioGranel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(52, Short.MAX_VALUE))
        );

        jLabel6.setBackground(new java.awt.Color(255, 255, 255));
        jLabel6.setFont(new java.awt.Font("Dialog", 1, 10)); // NOI18N
        jLabel6.setText("Esta ventana le permitira agregar un nuevo articulo al Stock");
        jLabel6.setOpaque(true);

        jPanel2.setBackground(new java.awt.Color(204, 204, 204));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/save.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jLabel10.setBackground(new java.awt.Color(204, 204, 204));
        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/warehouse.png"))); // NOI18N
        jLabel10.setOpaque(true);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(btnCancelar)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnGuardar, jLabel10});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel10)
                .addContainerGap())
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnCancelar, btnGuardar});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jpnStock, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpnStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private boolean revisaDuplicado(String producto) {
        try{
        ControlStock cs = new ControlStock();
        if (cs.selectOneByNameToStock(producto) != null) {
            return true;
        }
        }catch(IndexOutOfBoundsException e){
            return false;
        }
        return false;
    }
    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try {
            if (txtNombre.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "El campo Nombre esta vacio");
                txtNombre.requestFocus();
            } else if (txtCantidad.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "El campo Cantidad esta vacio");
                txtCantidad.requestFocus();
            } else if (txtMinimo.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "El campo Minimo esta vacio");
                txtMinimo.requestFocus();
            } else if (txtPrecioGranel.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "El campo Precio esta vacio");
                txtPrecioGranel.requestFocus();
            } else if (Integer.parseInt(txtCantidad.getText()) <= 0) {
                JOptionPane.showMessageDialog(this, "La cantidad del artículo debe ser mayor de 0");
                txtCantidad.requestFocus();
                txtCantidad.selectAll();
            } else if (Integer.parseInt(txtMinimo.getText()) <= 0) {
                txtMinimo.requestFocus();
                txtMinimo.selectAll();
                JOptionPane.showMessageDialog(this, "El mínimo del artículo debe ser mayor de 0");
            } else if (Integer.parseInt(txtPrecioGranel.getText()) <= 0) {
                JOptionPane.showMessageDialog(this, "El precio del artículo debe ser mayor de 0");
                txtPrecioGranel.requestFocus();
                txtPrecioGranel.selectAll();
            } else {

                if (revisaDuplicado(txtNombre.getText())) {
                    JOptionPane.showMessageDialog(this, "Se ha encontrado un elemento con el mismo nombre", "Error de duplicados", 0);
                    txtNombre.setText("");
                } else {
                    ControlStock cs = new ControlStock();
                    String[] idProveedor = cmbProveedor.getSelectedItem().toString().split("-");
                    ControlProviders cp = new ControlProviders();
                    Proveedores pro = (Proveedores) cp.selectOne(Integer.parseInt(idProveedor[0]));
                    try {
                        cs.add(txtNombre.getText(), Integer.parseInt(txtCantidad.getText()),
                                Short.parseShort(txtMinimo.getText()),
                                Float.parseFloat(txtPrecioGranel.getText()),
                                pro);
                        limpiarCampos();
                        JOptionPane.showMessageDialog(this, "¡Stock guardado con exito!","Guardado",1);
                    } catch (NumberFormatException | HeadlessException e) {
                        throw e;
                    }//Fin Try Catch
                }
            }//Fin if
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error:"+"\n"+e,"Ha ocurrido un error",0);
        }

    }//GEN-LAST:event_btnGuardarActionPerformed

    private void limpiarCampos() {
        txtCantidad.setText("0");
        txtCantidad.setText("0");
        txtMinimo.setText("0");
        txtPrecioGranel.setText("0");
        txtNombre.setText("");
    }

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtCantidadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCantidadKeyTyped
        char key = evt.getKeyChar();
        if ((key < '0' || key > '9') && (key != '\b') && (key != '\n')) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permiten numeros en "
                    + "este campo", "Letras no permitidas", 0);
        }
        if (txtCantidad.getText().length() > 5) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permite un largo maximo"
                    + " de 5 digitos en este campo.", "Maximo de digitos alcanzado", 0);
        }
    }//GEN-LAST:event_txtCantidadKeyTyped

    private void txtMinimoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMinimoKeyTyped
        char key = evt.getKeyChar();
        if ((key < '0' || key > '9') && (key != '\b') && (key != '\n')) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permiten numeros en "
                    + "este campo", "Letras no permitidas", 0);
        }
        if (txtCantidad.getText().length() > 5) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permite un largo maximo"
                    + " de 5 digitos en este campo.", "Maximo de digitos alcanzado", 0);
        }// TODO add your handling code here:
    }//GEN-LAST:event_txtMinimoKeyTyped

    private void txtPrecioGranelKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioGranelKeyTyped
        char key = evt.getKeyChar();
        if ((key < '0' || key > '9') && (key != '\b') && (key != '\n')) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permiten numeros en "
                    + "este campo", "Letras no permitidas", 0);
        }
        if (txtCantidad.getText().length() > 5) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permite un largo maximo"
                    + " de 5 digitos en este campo.", "Maximo de digitos alcanzado", 0);
        }// TODO add your handling code here:
    }//GEN-LAST:event_txtPrecioGranelKeyTyped
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Cantidad;
    private javax.swing.JLabel Precio;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbProveedor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JPanel jpnStock;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtMinimo;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtPrecioGranel;
    // End of variables declaration//GEN-END:variables

    private void CargaCombo() {
        //Controles para llenar los comoboBox
        ControlProviders cp = new ControlProviders();
        List listProviders = cp.selectAll();
        //Llenado de comboBox
        try {
            if (listProviders.size() > 0) {
                //Crea la lista de cproveedores
                for (int i = 0; i < listProviders.size(); i++) {
                    Proveedores proveedor = (Proveedores) listProviders.get(i);
                    cmbProveedor.addItem(proveedor.getIdproveedor() + "-" + proveedor.getNombre());
                }
            } else {
                deshabilitaControles();
                JOptionPane.showMessageDialog(this, "No hay Proveedores registrados" + "\n"
                        + "Antes de poder crear stock debe tener al menos un Proveedor.", "No hay Proveedores",
                        2);
                return;
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error al intentar obtener los proveedores. El error es:" + "\n" + e, "Error", 0);
        }
    }

    private void deshabilitaControles() {
        jpnStock.setEnabled(false);
        txtCantidad.setEnabled(false);
        txtMinimo.setEnabled(false);
        txtNombre.setEnabled(false);
        txtPrecioGranel.setEnabled(false);
        cmbProveedor.setEnabled(false);
        btnGuardar.setEnabled(false);
    }
}
